<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: pink;
            position: absolute;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <script>
        // 事件：1.鼠标按下的事件2.鼠标移动3.鼠标抬起
        // 获取元素

        var obox = document.querySelector(".box");
        // 鼠标按下时
        obox.onmousedown = function(e) {
            console.log("按下");
            // console.log(obox.offsetTop);
            // console.log(e.clientX);
            var x = e.clientX - obox.offsetLeft;
            var y = e.clientY - obox.offsetTop;

            //移动
            obox.onmousemove = function(e) {
                console.log("移动");
                var xx = e.clientX;
                var sx = xx - x;
                var yy = e.clientY;
                var sy = yy - y;
                obox.style.left = sx + "px";
                obox.style.top = sy + "px";
            };
        };
    </script>
</body>

</html>